import webSocketManager from '@/utils/websocket.js'

const state = {
  isConnected: false,
  lastMessageTime: null,
  unreadCount: 0,
  notifications: []
}

const mutations = {
  // 更新连接状态
  SET_CONNECTION_STATUS(state, status) {
    state.isConnected = status;
  },
  
  // 更新最后收到消息的时间
  SET_LAST_MESSAGE_TIME(state, time) {
    state.lastMessageTime = time;
  },
  
  // 增加未读消息数量
  INCREMENT_UNREAD_COUNT(state) {
    state.unreadCount++;
  },
  
  // 减少未读消息数量
  DECREMENT_UNREAD_COUNT(state) {
    if (state.unreadCount > 0) {
      state.unreadCount--;
    }
  },
  
  // 重置未读消息数量
  RESET_UNREAD_COUNT(state) {
    state.unreadCount = 0;
  },
  
  // 添加通知
  ADD_NOTIFICATION(state, notification) {
    // 限制通知列表最大长度为20
    if (state.notifications.length >= 20) {
      state.notifications.pop();
    }
    state.notifications.unshift(notification);
  },
  
  // 清空通知
  CLEAR_NOTIFICATIONS(state) {
    state.notifications = [];
  }
}

const actions = {
  // 连接WebSocket
  connect({ commit }, userId) {
    if (!userId) {
      userId = uni.getStorageSync('userId');
      if (!userId) {
        console.warn('无法连接WebSocket: 未找到用户ID');
        return Promise.reject('未找到用户ID');
      }
    }
    
    // 添加状态变更的监听器
    webSocketManager.addListener('vuex-status-monitor', (message) => {
      // 更新连接状态
      commit('SET_CONNECTION_STATUS', webSocketManager.isConnected);
      
      // 处理消息
      if (message) {
        // 更新最后收到消息的时间
        commit('SET_LAST_MESSAGE_TIME', new Date().getTime());
        
        // 增加未读消息数量
        //commit('INCREMENT_UNREAD_COUNT');
        
        // 添加通知
        try {
          let notification = {
            id: Date.now(),
            time: new Date().getTime(),
            type: message.type,
            message: message
          };
          
          commit('ADD_NOTIFICATION', notification);
        } catch (error) {
          console.error('处理通知失败:', error);
        }
      }
    });
    
    // 初始化WebSocket连接
    return new Promise((resolve, reject) => {
      try {
        webSocketManager.init({ userId });
        commit('SET_CONNECTION_STATUS', webSocketManager.isConnected);
        resolve(webSocketManager.isConnected);
      } catch (error) {
        console.error('连接WebSocket失败:', error);
        reject(error);
      }
    });
  },
  
  // 断开WebSocket连接
  disconnect({ commit }) {
    return new Promise((resolve) => {
      try {
        webSocketManager.close();
        commit('SET_CONNECTION_STATUS', false);
        resolve(true);
      } catch (error) {
        console.error('断开WebSocket连接失败:', error);
        resolve(false);
      }
    });
  },
  
  // 发送消息
  sendMessage({ commit }, message) {
    return new Promise((resolve, reject) => {
      try {
        const result = webSocketManager.send(message);
        resolve(result);
      } catch (error) {
        console.error('发送WebSocket消息失败:', error);
        reject(error);
      }
    });
  },
  
  // 重置未读消息数量
  resetUnreadCount({ commit }) {
    commit('RESET_UNREAD_COUNT');
  },
  
  // 清空通知
  clearNotifications({ commit }) {
    commit('CLEAR_NOTIFICATIONS');
  }
}

const getters = {
  isConnected: (state) => state.isConnected,
  unreadCount: (state) => state.unreadCount,
  lastMessageTime: (state) => state.lastMessageTime,
  notifications: (state) => state.notifications
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 